﻿using JESAI.EventBus.Attributes;
using JESAI.EventBus.Contexts;
using JESAI.EventBus.EventBusStores;
using JESAI.EventBus.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace JESAI.EventBus.SubscribeManagers
{
    public class EventSubscribeManager : IEventSubscribeManager
    {
        private readonly IEventStore _eventStore;
        public EventSubscribeManager(IEventStore eventStore)
        {
            _eventStore = eventStore;
        }

        public async Task Subscribe(string eventId, Func<EventExecutingContext, Task> handle, EventSubscribeAttribute attribute = null, MethodInfo handleMethod = null, CancellationToken cancellationToken = default)
        {
            if (handleMethod == null)
            {
                throw new ArgumentException("Handle method cannot be null");
            }

            if (string.IsNullOrWhiteSpace(eventId))
            {
                throw new ArgumentException("EventId method cannot be null");
            }

            await _eventStore.Push(new SubscribeEvent(eventId, EventSubscribeType.Subscribe)
            {
                Handle = handle,
                Attribute = attribute,
                HandleMethod = handleMethod
            }, cancellationToken);
        }

        public async Task Unsubscribe(string eventId, CancellationToken cancellationToken = default)
        {

            if (eventId == null) throw new ArgumentNullException(nameof(eventId));

            await _eventStore.Push(new SubscribeEvent(eventId, EventSubscribeType.Unsubscribe), default);
        }
    }
}
